package cn.ibizlab.core.authentication.provider;

import cn.ibizlab.core.authentication.domain.AuthProvider;
import cn.ibizlab.util.errors.BadRequestAlertException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 认证服务管理器，根据配置返回对应的服务认证服务
 */
@Component
public class DefaultAuthenticationServiceManager implements AuthenticationServiceManager {

    private List<AuthenticationServiceFactory> authenticationServiceFactory = new ArrayList<>();

    @Override
    public AuthenticationService getAuthenticationService(AuthProvider provider) {
        for(AuthenticationServiceFactory AuthenticationServiceFactory : getAuthenticationServiceFactory()){
            if(!AuthenticationServiceFactory.supports(provider))
                continue;

            return AuthenticationServiceFactory.getAuthenticationService(provider);
        }
        throw new BadRequestAlertException(String.format("没有找到类型[%1$s]可用的认证服务配置",provider.getAuthenticationType()),"","");
    }

    @Override
    public boolean registerAuthenticationServiceFactory(AuthenticationServiceFactory factory) {
        if(!authenticationServiceFactory.contains(factory))
            authenticationServiceFactory.add(factory);
        return true;
    }

    public List<AuthenticationServiceFactory> getAuthenticationServiceFactory() {
        return authenticationServiceFactory;
    }
}
